package com.pshare.tool;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;

import org.apache.log4j.Logger;

import com.pshare.util.SysPropertyUtils;

/**
 * 文件类空间的demo
 */
public class UpYunFileTool {
	
	private static final Logger logger = Logger.getLogger(UpYunFileTool.class);

	// 运行前先设置好以下三个参数
	private static final String BUCKET_NAME = SysPropertyUtils.getProperty("upyun.video.bucket");
	private static final String OPERATOR_NAME = SysPropertyUtils.getProperty("upyun.user");
	private static final String OPERATOR_PWD = SysPropertyUtils.getProperty("upyun.password");


	private static final String DIR = "/";

	private static UpYun upyun = null;
	
	static {
		// 初始化空间
		upyun = new UpYun(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
		// ****** 可选设置 begin ******

		// 切换 API 接口的域名接入点，默认为自动识别接入点
		// upyun.setApiDomain(UpYun.ED_AUTO);

		// 设置连接超时时间，默认为30秒
		// upyun.setTimeout(60);

		// 设置是否开启debug模式，默认不开启
		// upyun.setDebug(true);

		// ****** 可选设置 end ******
	}

	/**
	 * 获取空间占用大小
	 */
	public static void getBucketUsage() {
		long usage = upyun.getBucketUsage();

		logger.info("空间总使用量：" + usage + "B");
		
	}

	/**
	 * 获取某个目录的空间占用大小
	 */
	public static void getFolderUsage() {

		// 带查询的目录，如 "/" 或 "/tmp"
		String dirPath = DIR;

		long usage = upyun.getFolderUsage(dirPath);

		logger.info("'" + dirPath + "'目录占用量： " + usage + "B");
		
	}

	/**
	 * 上传文件
	 * 
	 * @throws IOException
	 */
	public static boolean uploadFile(InputStream is, String filePath) throws IOException {
		upyun.setContentMD5(UpYun.md5(is));
		is.reset();
		
		boolean result = upyun.writeFile(filePath, is, true);
		logger.info("上传到 " + filePath + isSuccess(result));
		return result;
	}
	
	/**
	 * 上传文件
	 * @param sourcePath 源文件路径
	 * @param targetPath 目标路径
	 * @return boolean
	 * @throws IOException
	 */
	public static boolean uploadFile(String sourcePath, String targetPath) throws IOException {
		File file = new File(sourcePath);
		upyun.setContentMD5(UpYun.md5(file));
		
		boolean result = upyun.writeFile(targetPath, file, true);
		logger.info("上传到 " + targetPath + isSuccess(result));
		return result;
	}
	
	public static boolean uploadFile(File file, String targetPath) throws IOException {
		upyun.setContentMD5(UpYun.md5(file));
		
		boolean result = upyun.writeFile(targetPath, file, true);
		logger.info("上传到 " + targetPath + isSuccess(result));
		return result;
	}
	
	/**
	 * 分块上传
	 * @param is
	 * @param filePath
	 * @return boolean
	 * @throws IOException
	 */
	public static boolean multiPartUpload(InputStream is, String filePath) throws IOException {
		// TODO 分4步
		
		return false;
	}

	/**
	 * 获取文件信息
	 */
	public static void getFileInfo(String filePath) {
		logger.info(filePath + " 的文件信息：" + upyun.getFileInfo(filePath));
	}

	/**
	 * 读取文件/下载文件
	 * 
	 * @throws IOException
	 */
	public static void readFile(String filePath) throws IOException {
		/*
		 * 方法1：直接读取文本内容
		 */
		String datas = upyun.readFile(filePath);
		logger.info(filePath + " 的文件内容:" + datas);

		/*
		 * 方法2：下载文件，采用数据流模式下载文件（节省内存）
		 */
		// 要写入的本地临时文件
		File file = File.createTempFile("upyunTempFile_", "");

		// 把upyun空间下的文件下载到本地的临时文件
		boolean result = upyun.readFile(filePath, file);
		logger.info(filePath + " 下载" + isSuccess(result) + "，保存到 "
				+ file.getAbsolutePath());
		
	}

	/**
	 * 删除文件
	 */
	public static void deleteFile(String filePath) {
		// 删除文件
		boolean result = upyun.deleteFile(filePath);

		logger.info(filePath + " 删除" + isSuccess(result));
	}

	/**
	 * 创建目录
	 */
	public static String mkDir() {
		Calendar cal = Calendar.getInstance();
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH) + 1;
		String filePath = DIR + year + month ;
		
		boolean result = upyun.mkDir(filePath, true);
		if (result) {
			return filePath;
		} else {
			return DIR;
		}
	}

	/**
	 * 读取目录下的文件列表
	 */
	public static void readDir(String path) {

		// 读取目录列表，将返回 List 或 NULL
		List<UpYun.FolderItem> items = upyun.readDir(path);

		if (null == items) {
			logger.info("'" + path + "'目录下没有文件。");

		} else {

			for (int i = 0; i < items.size(); i++) {
				logger.info(items.get(i));
			}

			logger.info("'" + path + "'目录总共有 " + items.size()
					+ " 个文件。");
		}

		
	}

	/**
	 * 删除目录
	 */
	public static void rmDir(String path) {
		boolean result = upyun.rmDir(path);
		logger.info("删除目录：" + path + isSuccess(result));
	}

	private static String isSuccess(boolean result) {
		return result ? " 成功" : " 失败";
	}
	
	public static boolean handleVideo(String path) {
		
		boolean result = upyun.handleVideo("/2014/10/y4tpjvtx.mov", false);
		logger.error(result);
		return result;
	}
}
